package com.qdxwx.manage.controller.coupon;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.DateUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.channel.ChannelService;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.coupon.CouponLimitService;
import com.qdxwx.data.service.coupon.CouponService;
import com.qdxwx.data.service.user.UserLetterService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.channel.Channel;
import com.qdxwx.models.coupon.Coupon;
import com.qdxwx.models.coupon.CouponCode;
import com.qdxwx.models.coupon.CouponLimit;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;
import java.util.Random;

/**
 * 优惠卷种类信息Controller
 */
@Controller
@RequestMapping("/coupon")
public class CouponEditController extends BaseController {

    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponLimitService couponLimitService;
    @Autowired
    private CouponCodeService couponCodeService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserLetterService userLetterService;
    @Autowired
    private ChannelService channelService;
    /**
     * 新增优惠卷种类信息
     */
    @GetMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        List<Channel> channels = channelService.getMenusByModuleId(ModuleType.COURSE.ordinal());
        mmap.put("channels", channels);
        return "coupon/coupon-edit";
    }

    /**
     * 新增保存优惠卷种类信息
     */
    @Log(title = "优惠卷种类信息", businessType = BusinessType.INSERT)
    @PostMapping("/add.json")
    @ResponseBody
    public AjaxResult addSave(HttpServletRequest request) {
        String title = request.getParameter("title");
        if (TKString.isEmpty(title)) return error("请输入优惠券名称");
        int limitAmount = Double.valueOf(TKConvert.toDouble(request.getParameter("limitAmount")) * 100).intValue();
        if (limitAmount <= 0) return error("请输入使用限额");
        int amount = Double.valueOf(TKConvert.toDouble(request.getParameter("amount")) * 100).intValue();
        if (amount <= 0) return error("请输入优惠金额");
        int useType = TKConvert.toInteger(request.getParameter("useType"), 1);
        long totalNum = TKConvert.toLong(request.getParameter("totalNum"), 1L);
        if (useType == 2 && totalNum > 5000) return error("生成数量不能超过5000张");
        int range = TKConvert.toInteger(request.getParameter("range"), 1);
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        String limitCourseId = request.getParameter("limitCourseId");
        switch (range) {
            case 2:
                if (categoryId < 1) return error("请选择专业");
                break;
            case 3:
                if (TKString.isEmpty(limitCourseId)) return error("请选择使用课程");
                break;
            default:
        }
        LocalDate startDate = TKConvert.toLocalDate(request.getParameter("startDate"));
        LocalDate endDate = TKConvert.toLocalDate(request.getParameter("endDate"));
        if (startDate.isAfter(endDate)) return error("到期时间必须大于开始时间");
        Coupon coupon = new Coupon();
        coupon.setTitle(title);
        coupon.setLimitAmount(limitAmount);
        coupon.setAmount(amount);
        coupon.setUseType(useType);
        coupon.setTotalNum(totalNum);
        coupon.setStartDate(startDate);
        coupon.setEndDate(endDate);
        coupon.setChannelId(categoryId);
        coupon.setManagerName(SessionUtils.getManager().getManagerName());
        int row = couponService.insert(coupon);
        if (row > 0) {
            Integer[] courseIds = TKConvert.toIntArray(limitCourseId);
            if (courseIds.length > 0) {
                for (int cid : courseIds) {
                    CouponLimit couponLimit = new CouponLimit();
                    couponLimit.setCouponId(coupon.getId());
                    couponLimit.setCourseId(cid);
                    couponLimitService.createCouponLimit(couponLimit);
                }
            }
            //适用范围为所有人只生成一张优惠券编码
            if (coupon.getUseType() == 1) totalNum = 1L;
            /*拼优惠券编码*/
            for (int i = 0; i < totalNum; i++) {
                String code = DateUtils.toString("yyyyMMddHHmmssSSS");
                code = handleStrValue(code + i);
                code = code.substring(0, 20);
                CouponCode couponCode = new CouponCode();
                couponCode.setCouponId(coupon.getId());
                couponCode.setStatus(1);
                couponCode.setUserId(0L);
                couponCode.setOrderNo("");
                couponCode.setCouponCode(code);
                couponCode.setIsRemind(0);
                couponCodeService.insert(couponCode);
            }
        }
        return toAjax(row);
    }
    
    @GetMapping("/give.html")
    public String give(HttpServletRequest request, ModelMap mmap){
        long id = TKConvert.toLong(request.getParameter("id"));
        if(id < 1) return error404;
        Coupon coupon = couponService.get(id);
        if(coupon == null) return error404;
        mmap.put("couponId",coupon.getId());
        return "coupon/coupon-give"; 
    }

    /**
     * 赠送优惠券编码
     */
    @RequestMapping("/give.json")
    @ResponseBody
    public AjaxResult giveCouponCode(HttpServletRequest request) {
        long couponId = TKConvert.toLong(request.getParameter("couponId"));
        long userId = TKConvert.toLong(request.getParameter("userId"));
        if (couponId < 1) return error("缺少优惠券id");
        Coupon coupon = couponService.get(couponId);
        if (coupon == null) return error("找不到指定优惠券");
        if (userId < 1) return error("请输入赠送用户Id");
        User user = userService.get(userId);
        if(user == null) return error("赠送用户Id不存在，userId="+userId);
        CouponCode couponCode = new CouponCode();
        couponCode.setCouponId(couponId);
        couponCode.setStatus(1);
        couponCode.setUserId(0L);
        List<CouponCode> courseCodeList = couponCodeService.getList(couponCode, new PageRequest(1,1));
        if (courseCodeList.size() < 1) return error("赠送失败，没有未赠送优惠券！");
        couponCode.setUserId(userId);
        couponCode.setUserName(user.getUserName());
        couponCode.setId(courseCodeList.get(0).getId());
        int row = couponCodeService.update(couponCode);
        if(row > 0){
            couponService.updateUseNum(coupon.getId());
        }
        return toAjax(row);
    }


    private static String handleStrValue(String value) {
        String[] sts = new String[]{"", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
                "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        StringBuilder buf = new StringBuilder(value);
        Random ran = new Random();
        for (int i = 0; i < 5; i++) {
            String key = sts[ran.nextInt(26)];
            int offset = ran.nextInt(value.length() - 1);
            buf.insert(offset, key);
        }
        return buf.toString();
    }

    /**
     * 删除优惠卷种类信息
     * 同时删除优惠券编码与课程关系表
     */
    @Log(title = "优惠卷种类信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request) {
        long id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error("参数异常");
        CouponCode couponCode = new CouponCode();
        couponCode.setCouponId(id);
        couponCode.setStatus(1);
        if (couponCodeService.count(couponCode) > 0) return error("还有部分优惠券尚未使用，不能删除");
        return toAjax(couponService.deleteById(id));
    }

}
